package com.android.myapplication.view.media;

import android.app.Activity;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.myapplication.R;

import androidx.appcompat.app.AlertDialog;

public class MediaActivity extends Activity implements View.OnClickListener {


    private Button btPlayMusicRaw;
    private Button btPlayMusicSdcard;
    private Button btPlayMusicWeb;
    private Button btPausedContinue;
    private Button btStop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_musice);
        initView();
        initListener();
        bindService(new Intent(this, MediaService.class), connection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 绑定服务
    }
    private void initView() {
        btPlayMusicRaw = findViewById(R.id.bt_play_music_raw);
        btPlayMusicSdcard  = findViewById(R.id.bt_play_music_sdcard);
        btPlayMusicWeb  = findViewById(R.id.bt_play_music_web);
        btPausedContinue = findViewById(R.id.bt_paused_continue);
        btStop = findViewById(R.id.bt_stop);

    }

    private void initListener() {
        btPlayMusicRaw.setOnClickListener(this);
        btPlayMusicSdcard.setOnClickListener(this);
        btPlayMusicWeb.setOnClickListener(this);
        btPausedContinue.setOnClickListener(this);
        btStop.setOnClickListener(this);
    }

    private IMusicePlay iMusicPlay;

    private ServiceConnection connection = new ServiceConnection() {
        /**
         * 连接到服务
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iMusicPlay = (IMusicePlay) service;
        }

        /**
         * 断开连接
         * @param name
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解绑服务：注意bindService后 必须要解绑服务，否则会报 连接资源异常
        if (null != connection) {
            unbindService(connection);
        }
    }

    // 音乐文件到路径
    private final String MUSIC_PATH = Environment.getExternalStorageDirectory() + "/mom.mp3";
    private final String MUSIC_PATH_WEB = "http://m8.music.126.net/20200331163634/ff99f3d787a6bac23779c0ca9d42c8ec/ymusic/560f/075e/535f/ae15cebedc04c39f79f6d5ac577f2977.mp3";

    @Override
    public void onClick(View v) {

        if (iMusicPlay == null) {
            Toast.makeText(this, "音乐播放服务连接失败", Toast.LENGTH_LONG).show();
            return;
        }
        try {

            switch (v.getId()) {

                case R.id.bt_play_music_raw:
                    iMusicPlay.playMusic(String.valueOf(R.raw.mom), 0);
                    break;
                case R.id.bt_play_music_sdcard:
                    iMusicPlay.playMusic(MUSIC_PATH, 1);
                    break;
                case R.id.bt_play_music_web:
                    iMusicPlay.playMusic(MUSIC_PATH_WEB, 2);
                    break;

                case R.id.bt_paused_continue:
                    if ("暂停播放".equals(btPausedContinue.getText().toString())) {
                        btPausedContinue.setText("继续播放");
                        iMusicPlay.pausedPlay();
                    } else {
                        btPausedContinue.setText("暂停播放");
                        iMusicPlay.continuePlay();
                    }
                    break;

                case R.id.bt_stop:
                    iMusicPlay.stopPlay();
                    break;

                default:
                    break;
            }
        }catch (RemoteException e){
            e.printStackTrace();
        }
    }

    /**
     * 用户按返回键，系统会调用到此方法
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);

        // 判断是否在播放，如果在播放中，才告知用户 弹出对话框
        if (iMusicPlay == null) {
            return true;
        }

        try {
            if(iMusicPlay.isPlaying()) {

                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        showAlertDialog();
                        break;
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 弹出对话框
     */
    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MediaActivity.this);
        builder.setTitle("提示");
        builder.setMessage("确定要关闭音乐播放？");
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNeutralButton("后台播放", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 既然是后台播放，就是要把当前Activity切换到后台
                moveTaskToBack(true);
            }
        });
        builder.setPositiveButton("取消", null);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}